import {IParams} from './params'
import * as fsPromises from 'fs/promises'
import {replaceEnvVar} from './util'
import * as step from '@flow-step/step-toolkit'

export async function replaceVariables(params: IParams){
    let data: string
    step.info(`Reading file ${params.sourceFilePath} using default utf-8 encoding`)
    try {
        data = await fsPromises.readFile(params.sourceFilePath, 'utf-8')
    } catch (error:any) {
        step.error(`Error reading file ${params.sourceFilePath}` )
        throw error
    }

    const replacedData = replaceEnvVar(data)
    try{
        await fsPromises.writeFile(params.targetFilePath, replacedData)
    }catch (e:any){
        step.error(`error writing file ${params.targetFilePath}`)
        throw e
    }
}